package com.easy.dfcapi.utils;

import com.easy.common.constant.CommonConstant;
import com.easy.common.util.AzDGCrypt;
import com.easy.common.util.CookieUtils;
import com.easy.common.util.IPUtil;
import com.easy.common.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;

/**
 * Created by mac on 2018/1/3.
 */
public class ServletHelper {

    private static String getCookieKey(String key) {
        return CommonConstant.COOKIE.PRIFIX + key;
    }

    public static void removeSession(HttpServletRequest request, HttpServletResponse response) {
        String domain = request.getScheme() + "://" + request.getServerName()+ ":" + request.getServerPort() + request.getContextPath();
        CookieUtils.removeCookie(getCookieKey(CommonConstant.COOKIE.USER_ID), domain, request, response);
        CookieUtils.removeCookie(getCookieKey(CommonConstant.COOKIE.USER_NAME), domain, request, response);
        CookieUtils.removeCookie(getCookieKey(CommonConstant.COOKIE.COOKIE_TOKEN), domain, request, response);
        CookieUtils.removeCookie(getCookieKey(CommonConstant.COOKIE.COOKIE_TIME), domain, request, response);
    }

    public static ApiSessionUser getSessionUser(HttpServletRequest request, HttpServletResponse response) {
        String domain = request.getScheme() + "://" + request.getServerName()+ ":" + request.getServerPort() + request.getContextPath();
        long cookieUserId = 0;
        String token = CookieUtils.getCookie(request, getCookieKey(CommonConstant.COOKIE.COOKIE_TOKEN));
        String cookieTimeStr = CookieUtils.getCookie(request, getCookieKey(CommonConstant.COOKIE.COOKIE_TIME));
        int cookieTime = 0;
        if (StringUtils.isBlank(token)) {
            return null;
        }
        if (StringUtils.isBlank(cookieTimeStr)) {
            return null;
        }
        try {
//			token = URLDecoder.decode(token, "utf-8");
            cookieUserId = Long.parseLong(CookieUtils.getCookie(request, getCookieKey(CommonConstant.COOKIE.USER_ID)));
            cookieTime = Integer.valueOf(cookieTimeStr);
        } catch (Exception e) {}
        if (cookieUserId == 0 || cookieTime == 0) {
            return null;
        }

        String tokenStr = AzDGCrypt.decrypt(token);
        if (StringUtils.isEmpty(tokenStr)) {
            return null;
        }
        String[] infos = tokenStr.split(",", 6);

        if (infos.length != 6) {
            return null;
        }
        int nowTime = (int)System.currentTimeMillis() / 1000;
        ApiSessionUser user = new ApiSessionUser();
        user.setUserId(Integer.valueOf(infos[1]));
        user.setStoreId(Integer.valueOf(infos[2]));
        user.setUserType(Integer.valueOf(infos[3]));
        user.setStoreType(Integer.valueOf(infos[4]));
        user.setUserName(infos[5]);
        user.setCreateTokenTime(Integer.valueOf(infos[0]));
        user.setLastRequestTime(cookieTime);
        user.setIp(IPUtil.getIpAddress(request));

        if (cookieUserId != user.getUserId()) {
            return null;
        }
        if (System.currentTimeMillis() / 1000 - user.getCreateTokenTime()  > CommonConstant.COOKIE_MAX_AGE.COOKIE_MAX_AGE) {
            return null;
        }

        if (nowTime - cookieTime > CommonConstant.COOKIE_MAX_AGE.MAX_AGE) {
            return null;
        }
        CookieUtils.setCookie(response, getCookieKey(CommonConstant.COOKIE.COOKIE_TIME), String.valueOf(nowTime), domain, CommonConstant.COOKIE_MAX_AGE.MAX_AGE);
        return user;
    }

    public static void setSessionKey(HttpServletRequest request, HttpServletResponse response, ApiSessionUser user) {
        String domain = request.getScheme() + "://" + request.getServerName()+ ":" + request.getServerPort() + request.getContextPath();
        int nowTime = (int)System.currentTimeMillis() / 1000;
        StringBuffer tokenStr = new StringBuffer();
        tokenStr.append(user.getCreateTokenTime());
        tokenStr.append(",");
        tokenStr.append(user.getUserId());
        tokenStr.append(",");
        tokenStr.append(user.getStoreId());
        tokenStr.append(",");
        tokenStr.append(user.getUserType());
        tokenStr.append(",");
        tokenStr.append(user.getStoreType());
        tokenStr.append(",");
        tokenStr.append(user.getUserName());
        user.setLastRequestTime(nowTime);
        String token = AzDGCrypt.encrypt(tokenStr.toString());
        try {
            CookieUtils.setCookie(response, getCookieKey(CommonConstant.COOKIE.COOKIE_TOKEN), URLEncoder.encode(token, "utf-8"), domain, CommonConstant.COOKIE_MAX_AGE.COOKIE_MAX_AGE);
            CookieUtils.setCookie(response, getCookieKey(CommonConstant.COOKIE.USER_ID), URLEncoder.encode(String.valueOf(user.getUserId()), "utf-8"), domain, CommonConstant.COOKIE_MAX_AGE.MAX_AGE);
            CookieUtils.setCookie(response, getCookieKey(CommonConstant.COOKIE.USER_NAME), URLEncoder.encode(user.getUserName(), "utf-8"), domain, CommonConstant.COOKIE_MAX_AGE.MAX_AGE);
            CookieUtils.setCookie(response, getCookieKey(CommonConstant.COOKIE.COOKIE_TIME), URLEncoder.encode(String.valueOf(nowTime), "utf-8"), domain, CommonConstant.COOKIE_MAX_AGE.MAX_AGE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ApiSessionUser getSessionUserByToken(String token) {
        ApiSessionUser user = null;
        if (StringUtils.isBlank(token)) {
            return null;
        }
        try {
//			token = URLDecoder.decode(token, "utf-8");
            String tokenStr = AzDGCrypt.decrypt(token);
            if (StringUtils.isEmpty(tokenStr)) {
                return null;
            }
            String[] infos = tokenStr.split(",", 6);
            if (infos.length != 6) {
                return null;
            }
            int nowTime = (int)System.currentTimeMillis() / 1000;
            user = new ApiSessionUser();
            user.setUserId(Integer.valueOf(infos[1]));
            user.setStoreId(Integer.valueOf(infos[2]));
            user.setUserType(Integer.valueOf(infos[3]));
            user.setStoreType(Integer.valueOf(infos[4]));
            user.setUserName(new String(infos[5].getBytes(), "utf8"));
            user.setCreateTokenTime(Integer.valueOf(infos[0]));
            user.setLastRequestTime(nowTime);
            user.setToken(token);
        } catch (Exception e) {}
        return user;
    }

    public static ApiSessionUser getSessionUserByToken(HttpServletRequest request) {
        return getSessionUserByToken(request.getParameter("token"));
    }

    public static String getTokenByUser(ApiSessionUser user) {
        int nowTime;
        try {
            nowTime = StringUtils.parseInt(System.currentTimeMillis() / 1000);
        } catch (Exception e) {
            nowTime = (int)(new Date().getTime() / 1000);
        }
        StringBuffer tokenStr = new StringBuffer();
        tokenStr.append(nowTime);
        tokenStr.append(",");
        tokenStr.append(user.getUserId());
        tokenStr.append(",");
        tokenStr.append(user.getStoreId());
        tokenStr.append(",");
        tokenStr.append(user.getUserType());
        tokenStr.append(",");
        tokenStr.append(user.getStoreType());
        tokenStr.append(",");
        tokenStr.append(user.getUserName());
        return AzDGCrypt.encrypt(tokenStr.toString());
    }
}
